﻿// Write a program that reads a text file containing a square matrix of numbers
// and finds in the matrix an area of size 2 x 2 with a maximal sum of its elements. 
// The first line in the input file contains the size of matrix N. 
// Each of the next N lines contain N numbers separated by space. 
// The output should be a single number in a separate text file. 

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"..\..\";

        string inputFileName = "matrix.txt";
        string inputFile = Path.Combine(path, inputFileName);

        string outputFileName = "MaxSubsetSum.txt";
        string outputFile = Path.Combine(path, outputFileName);

        try
        {
            string[] fileLinesArray = File.ReadAllLines(inputFile);

            int matrixSize = int.Parse(fileLinesArray[0]);
            int[,] matrix = new int[matrixSize, matrixSize];

            for (int i = 1; i < fileLinesArray.Length; i++)
            {
                string[] currentLine = fileLinesArray[i].Split();
                for (int j = 0; j < currentLine.Length; j++)
                {
                    matrix[i - 1, j] = int.Parse(currentLine[j]);
                }
            }

            int maxSubsetSum = GetMaxSubsetSum(matrix, 2);
            File.WriteAllText(outputFile, maxSubsetSum.ToString());

            Console.WriteLine("New file with result created: {0}", outputFile);
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc.Message);
        }
    }

    private static int GetMaxSubsetSum(int[,] matrix, int squareSize)
    {
        int bestSum = int.MinValue;
        int bestRow = 0;
        int bestCol = 0;

        for (int row = 0; row < matrix.GetLength(0) - squareSize + 1; row++)
        {
            for (int col = 0; col < matrix.GetLength(1) - squareSize + 1; col++)
            {
                // sum elements of square
                int sum = 0;
                for (int squareRow = row; squareRow < row + squareSize; squareRow++)
                {
                    for (int squareCol = col; squareCol < col + squareSize; squareCol++)
                    {
                        sum += matrix[squareRow, squareCol];
                    }
                }

                if (sum > bestSum)
                {
                    bestSum = sum;
                    bestRow = row;
                    bestCol = col;
                }
            }
        }

        return bestSum;
    }
}